#!/bin/sh

#
# 编译安装软件启动管理脚本
#

set -e

#  服务名  
PROGNAME=$1

PROGDIR=/usr/local/$PROGNAME
#PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin:$PROGDIR/sbin  
PATH=$PROGDIR/sbin:$PATH
DAEMON=$PROGDIR/sbin/$PROGNAME
CONFIG=$PROGDIR/conf/$PROGNAME.conf
PIDFILE=$PROGDIR/run/$PROGNAME.pid
DESC="$PROGNAME daemon"
 
# Gracefully exit if the package has been removed.
test -x $DAEMON || exit 0  

usage_check(){
    if [ -z $PROGNAME ] ;then
        usage
    fi
}
usage_check

usage(){
    echo "Usage: $0 service_name {start|stop|restart|reload}" >&2
    exit 1
}

get_pid(){
    local prog_pid
    if [ -f $PROGDIR/run/$PROGNAME.pid ] ;then
        prog_pid=`cat $PIDFILE`
        echo ${prog_pid}
    fi
}
 
do_start(){  
        local prog_pid=`get_pid()`
        if [ ".${prog_pid}"=="." ] ;then
            echo -n "Starting $DESC: $PROGNAME"
            $DAEMON -f $CONFIG
            echo "."
        else
            echo -n "$PROGNAME already running"
        fi
}
 
do_stop(){  
        local prog_pid=`get_pid()`
        if [ ".${prog_pid}"!="." ] ;then  
            echo -n "Stopping $DESC: $PROGNAME"
            kill $prog_pid  
            echo "."  
        else
            echo -n "$PROGNAME not running"
        fi            
}
 
do_reload(){  
        local prog_pid=`get_pid()`
        if [ ".${prog_pid}"!="." ] ;then  
            echo -n "Restarting $DESC: $PROGNAME"
            #haproxy
            $DAEMON -f $CONFIG -p $PIDFILE -sf $(cat $PIDFILE)
            echo "."  
        else
            echo -n "$PROGNAME can't reload"
        fi  
}
 
case "$2" in
  start)
        do_start
        ;;
  stop)
        do_stop
        ;;
  reload)
        do_reload
        ;;
  restart)
        do_stop
        do_start
        ;;
  *)
        usage
        ;;
esac

exit 0